package com.klst.opennlp;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.util.logging.Logger;

import opennlp.tools.util.InputStreamFactory;

public class TigerInputStreamFactory implements InputStreamFactory {
  
  private final static Logger LOG = Logger.getLogger(TigerInputStreamFactory.class.getName());
  
  private File file = null;
  
  public TigerInputStreamFactory(String uri) throws FileNotFoundException {
    LOG.fine("ctor uri="+uri);
    this.file = new File(uri);
  }

  /*
   * es wird ein InputStream aus Sätzen geliefert
   */
  @Override
  public InputStream createInputStream() throws IOException {
    PipedInputStream sinkPis = new TigerInputConsumer();
    TigerSentenceSource dataPipe = new TigerSentenceSource(sinkPis, this.file);
    
    Thread producerThread = new Thread(dataPipe);
    producerThread.start();
    // den consumerThread braucht man nur zum Testen:
//    Thread consumerThread = new Thread((Runnable) sinkPis);
//    consumerThread.start();
    
    return sinkPis;
  }

  // ------------------- Test:
  static final String RESOURCES_DIR = "src/test/resources/opennlp/";
  static final String SAMPLE_XML = "tiger-mini.xml";
  
  public static void main(String[] args) {
    try {
      long past = System.currentTimeMillis();
      InputStreamFactory inputStreamFactory = new TigerInputStreamFactory(RESOURCES_DIR + SAMPLE_XML);
      InputStream sinkPis = inputStreamFactory.createInputStream();
      Thread consumerThread = new Thread((Runnable) sinkPis);
      consumerThread.start();
      consumerThread.join();
      long now = System.currentTimeMillis();
      LOG.info("Test input: "+SAMPLE_XML + " Time taken: " + (now - past) + " ms");
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}
